package com.maxd.modules.chat.service;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.modules.chat.entity.Chat;
import com.maxd.modules.chat.entity.ChatContent;
import com.maxd.modules.chat.respository.ChatContentRepository;
import com.maxd.modules.chat.respository.ChatRepository;
import com.maxd.modules.selfshop.merchants.entity.SelfStore;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    private ChatRepository jpaRepository;
    @Autowired
    private ChatContentRepository chatContentRepository;
    @Autowired
    private SelfStoreJpaRepository selfStoreJpaRepository;

    @Override
    public Result count(Long storeId) {
        Integer count = jpaRepository.count(storeId);
        if (count == null){
            return ResultUtil.success(0);
        }
        return ResultUtil.success(count);
    }

    @Override
    public Result userCount(String userId) {
        Integer count = jpaRepository.sumUserCount(userId);
        if (count == null){
            return ResultUtil.success(0);
        }
        return ResultUtil.success(count);
    }

    /**
     * 商家端会话列表
     * @param storeId
     * @return
     */
    @Override
    public Result findAll(Long storeId, String userName) {
        //构造自定义查询条件
        Specification<Chat> queryCondition = new Specification<Chat>() {
            @Override
            public Predicate toPredicate(Root<Chat> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("storeId"), storeId));
                if (StringUtils.isNotEmpty(userName)){
                    predicateList.add(criteriaBuilder.like(root.get("userName"), "%"+userName+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<Chat> list = jpaRepository.findAll(queryCondition, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //最新一条消息展示
        List<ChatContent> allContent = chatContentRepository.findAll();
        for (Chat c : list) {
            for (ChatContent cc : allContent) {
                if (c.getChatId().equals(cc.getChatId())){
                    c.setContent(cc.getContent());
                    c.setContentTime(cc.getCreateTime());
                }
            }
        }
        return ResultUtil.success(list);
    }

    /**
     * 用户端会话列表
     * @param userId
     * @return
     */
    @Override
    public Result userList(String userId, String storeName) {
        //构造自定义查询条件
        Specification<Chat> queryCondition = new Specification<Chat>() {
            @Override
            public Predicate toPredicate(Root<Chat> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                if (StringUtils.isNotEmpty(storeName)){
                    predicateList.add(criteriaBuilder.like(root.get("storeName"), "%"+storeName+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<Chat> list = jpaRepository.findAll(queryCondition, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //最新一条消息展示
        List<ChatContent> allContent = chatContentRepository.findAll();
        for (Chat c : list) {
            for (ChatContent cc : allContent) {
                if (c.getChatId() == cc.getChatId()){
                    c.setContent(cc.getContent());
                    c.setContentTime(cc.getCreateTime());
                }
            }
        }
        return ResultUtil.success(list);
    }

    /**
     * 用户端发起聊天
     * @param entity
     * @return
     */
    @Override
    public Result saveBody(Chat entity) {
        //判断是否存在聊天
        List<Chat> chatList = jpaRepository.findByUserIdAndStoreId(entity.getUserId(), entity.getStoreId());
        if (chatList.size() > 0){
            Chat chat = chatList.get(0);
            return ResultUtil.success(chat);
        }else {
            //不存在会话，创建会话
            entity.setCreateTime(DateUtil.createTime());
            entity.setStoreCount(0);
            entity.setUserCount(0);
            Chat save = jpaRepository.save(entity);
            if(entity.getStoreId()!=null && entity.getStoreId()!=0){
                SelfStore selfStore = selfStoreJpaRepository.findById(entity.getStoreId()).orElse(null);
                if(selfStore!=null && StringUtils.isNotEmpty(selfStore.getMsgContent())){
                    ChatContent entitys=new ChatContent();
                    entitys.setContent(selfStore.getMsgContent());
                    entitys.setType(1);
                    entitys.setSendType(2);
                    entitys.setUserId(entity.getUserId());
                    entitys.setStoreId(entity.getStoreId());
                    entitys.setChatId(save.getChatId());
                    entitys.setCreateTime(DateUtil.createTime());
                    entitys.setStatus(2); //未读
                    chatContentRepository.save(entitys);
                }

            }

            return ResultUtil.success(save);
        }
    }

    @Override
    public Result updateBody(Chat entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }


    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id); //删除会话
        chatContentRepository.deleteAllByChatId(id); //删除会话聊天内容
        return ResultUtil.success();
    }

}
